// +----------------------------------------------------------------------
// | bossHongshi [鸿时互娱管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.hongshihuyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wgh
// +----------------------------------------------------------------------
const fly=require("flyio")
module.exports = class extends think.cmswing.center {
  async __before() {
    await super.__before();
    // 判断是否登陆
    // await this.weblogin();
    if (!this.is_login) {
      // 判断浏览客户端
      if (this.isMobile) {
        // 手机端直接跳转到登录页面
        return this.redirect('/center/public/login');
      } else {
        return this.redirect('/cmswing/error/login');
      }
    }
  }
  // 我的的俱乐部
  async indexAction() {
    const club_no = this.para('club_no') || null;
    
//    const gameserver = this.service('cmswing/gameserver', this.ctx);
//    let clubsPromise  = think.promisify(gameserver.getclubs);
//    const clubs = await clubsPromise();
//    console.log('clubs data--------------2222----:'+JSON.stringify(clubs));
    
  //发送Get请求
	  const url='http://47.97.119.70:17100/club?uid=28&area=niuniuBackend&cmd=queryClub&sign=password';
	  /**
	  http.get(url,function(req,res){
	  	var html='';
	  	req.on('data',function(data){
	  		console.log('data--------------:'+data);
	  	});
	  	req.on('end',function(){
	  		console.info(html);
	  	});
	  });
	  */
	  
	  fly.config.timeout=10000;
	  fly.config.parseJson=true;
	  
	  let ret = await fly.get(url);
	  console.log('ret ------------------1111111:'+ret.data);
	  let clubdata = JSON.parse(ret.data);
	  console.log('arr--------------11----:'+JSON.stringify(clubdata.data.arr));
	  this.assign('clublist', clubdata.data.arr);
//	  fly.get(url)
//	  .then(function (response) {
//		  let clubdata = JSON.parse(response.data);
//		console.log('response  arr--------------bb----:'+JSON.stringify(clubdata.data.arr));
//	  })
//	  .catch(function (error) {
//	    console.log(error);
//	  });
//	  console.log('response  arr--------------bb----:'+JSON.stringify(clubdata.data.arr));
	 
    // 筛选订单
    let map;
    if (think.isEmpty(club_no)) {
        map = {
                status: ['IN', [0,1,2]],
                uid: this.user.uid
              };
    }else{
    	 map = {
                 status: ['IN', [0,1,2]],
                 uid: this.user.uid,
                 club_no: ['LIKE', '%' + club_no + '%']
               };
    }
    const userInfo = await this.model('member').find(this.user.uid);
    this.assign('userInfo', userInfo);
    const data = await this.model('club').where(map).page(this.para('page')).order('create_time DESC').countSelect();
    const html = this.pagination(data);
    this.assign('pagination', html);
    
    // 未付款统计
    const totalid = await this.model('club').where(map).count('id');
    this.assign('totalid', totalid);
    this.assign('count', data.count);
//    console.log('数据列表  --------------111----:'+JSON.stringify(data.data));
    this.assign('list', data.data);
    this.meta_title = '我的俱乐部';
    // 判断浏览客户端
    if (this.isMobile) {
      if (this.isAjax('get')) {
        for (const v of data.data) {
          v.create_time = this.moment(v.create_time).format('lll');
        }
        return this.json(data);
      } else {
        this.active = 'club/index';
        return this.display(this.mtpl());
      }
    } else {
      return this.display();
    }
  }

  /**
   * 注册俱乐部
   */
  async createAction() {
    if (this.isAjax('POST')) {
      const data = this.post();
      if (think.isEmpty(data.club_name)) {
        return this.fail('请输入俱乐部名称！');
      } else if (data.club_name.length>10){
        return this.fail('俱乐部名称太长！');
      }
      
      console.log('创建俱乐部--post data:'+JSON.stringify(data));
      // 用户
      data.user_id = this.user.uid;
      const userInfo = await this.model('member').find(this.user.uid);
      let  update =false;
      if(userInfo.card_count<1000){
    	  return this.fail('您的房卡不够！');
      }else{
    	  update = await this.model('member').where({id:data.user_id}).decrement('card_count',1000);
      }
      console.log('创建俱乐部--update data:'+update);
      if (update) {
    	// 创建俱乐部
    	  const createTime = new Date().getTime();
    	  const timestr = createTime.toString();
    	  
    	  const club = {
    	          uid: data.user_id,
    	          club_no: timestr.substr(7),
    	          club_name: data.club_name,
    	          create_time:createTime,
    	          type:0,
    	          status:1,
    	          card_count:1000
    	   };
    	let  create =  await this.model('club').add(club);
    	if(create){
    		return this.success({name:'创建成功！'});
    	}else{
    		return this.fail('创建失败！');
    	}
        
      } else {
        return this.fail('创建失败！');
      }
      
    } else {
      // 获取用户信息
//      const createTime = new Date().getTime();
//  	  const timestr = createTime.toString();
//  	  console.log('timestr. data---------:'+timestr);
//  	  console.log('timestr.substr(5) data---------:'+timestr.substr(5));
      const userInfo = await this.model('member').find(this.user.uid);
      this.assign('userInfo', userInfo);
      
      this.meta_title = '创建俱乐部';
      if (this.isMobile) {
        this.active = 'club/index';
        return this.display(this.mtpl());
      } else {
        this.display();
      }
    }
  }
  
  /**
   * 添加俱乐部成员
   */
  async addplayerAction() {
    if (this.isAjax('POST')) {
      const data = this.post();
      console.log('添加俱乐部成员--post data:'+JSON.stringify(data));
      const playerid = this.para('playerid') || null;
      const clubid = this.para('clubid') || null;
      console.log('添加俱乐部成员--post playerid data:'+playerid);
      console.log('添加俱乐部成员--post clubid data:'+clubid);
      // 用户
      data.user_id = this.user.uid;
      const clubplayer = await this.model('club_player').where({club_id:clubid, player_id:playerid}).find();
      console.log('俱乐部--post clubid data-11111111111:'+clubid);
      if(!think.isEmpty(clubplayer)){
    	  console.log('俱乐部--post clubid data-2222222222:'+clubid);
		  if(clubplayer.status==1){
			  console.log('俱乐部--post clubid data-33333333333:'+clubid);
			  return this.success({name:'成员已在俱乐部！'});
		  }else if(clubplayer.status==-2||clubplayer.status==2||clubplayer.status==3){
			  console.log('俱乐部--post clubid data-4444444444:'+clubid);
			  const res = await this.model('club_player').where({club_id:clubid, player_id:playerid}).update({status:1});
			  if (res) {
			    	// 邀请俱乐部成员
			        return this.success({name:'邀请加入成功！'});
			  }else{
			    	return this.fail('邀请加入失败！');
			  }
		  }
	  }else{
		// 创建俱乐部
		  console.log('俱乐部--post clubid data-55555555555:'+clubid);
    	  const createTime = new Date().getTime();
    	  const clubInfo = await this.model('club').find(clubid);
    	  
    	  let map = {
	                 status: ['IN', [1]],
	                 uid: this.user.uid,
	                 player_id:playerid 
	      };

	      const mpInfo = await this.model('member_player').where(map).find();
	    
    	  const cp = {
    	          club_id: clubid,
    	          club_no: clubInfo.club_no,
    	          player_id:playerid,
    	          player_name:mpInfo.player_name,
    	          status:1,
    	          create_time:createTime
    	   };
    	  console.log('俱乐部--post clubid data-666666666:'+clubid);
    	let  create =  await this.model('club_player').add(cp);
    	if(create){
    		 console.log('俱乐部--post clubid data-7777777777:'+clubid);
    		return this.success({name:'邀请加入成功！'});
    	}else{
    		return this.fail('邀请加入失败！');
    	}
    	
	  }
      
    } else {
      // 获取用户信息
      //const userInfo = await this.model('member').find(this.user.uid);
      //this.assign('userInfo', userInfo);
    	const clubid = this.para('clubid') || null;
    	this.assign('clubid', clubid);
      this.meta_title = '添加成员';
      if (this.isMobile) {
        this.active = 'club/player/index';
        return this.display(this.mtpl());
      } else {
        this.display();
      }
    }
  }
  
  // 俱乐部成员
  async playerAction() {
	if (this.isAjax('POST')) {
		const player_id = this.para('playerid') || null;
		const club_id = this.para('clubid') || null;
		const opt = this.para('opt') || null;
		if(opt==2){
			console.log('删除俱乐部成员--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).delete();
		    if (res) {
		    	// 删除俱乐部成员
		        return this.success({name:'删除成功！'});
		    }else{
		    	return this.fail('删除失败！');
		    }
		}else if(opt==0){
			console.log('设为管理员--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({is_admin:1});
			if (res) {
		    	// 设为管理员
		        return this.success({name:'设为管理员成功！'});
		    }else{
		    	return this.fail('设为管理员失败！');
		    }
		}else if(opt==1){
			console.log('取消管理员--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({is_admin:0});
			if (res) {
		    	// 取消管理员
		        return this.success({name:'取消管理员成功！'});
		    }else{
		    	return this.fail('取消管理员失败！');
		    }
		}else if(opt==3){
			console.log('同意入会--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({status:1});
			if (res) {
		    	// 同意入会
		        return this.success({name:'同意入会成功！'});
		    }else{
		    	return this.fail('同意入会失败！');
		    }
		}else if(opt==4){
			console.log('拒绝入会--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({status:3});
			if (res) {
		    	// 拒绝入会
		        return this.success({name:'拒绝入会成功！'});
		    }else{
		    	return this.fail('拒绝入会失败！');
		    }
		}else if(opt==5){
			console.log('同意离会--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({status:-2});
			if (res) {
		    	// 同意入会
		        return this.success({name:'同意离会成功！'});
		    }else{
		    	return this.fail('同意离会失败！');
		    }
		}else if(opt==6){
			console.log('拒绝离会--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({status:1});
			if (res) {
		    	// 拒绝入会
		        return this.success({name:'拒绝离会成功！'});
		    }else{
		    	return this.fail('拒绝离会失败！');
		    }
		}
		
	}else{
		const status = this.para('status') || null;
	    const club_id = this.para('clubid') || null;
	    let map;
	    
	    // 筛选订单
	    //2：未审核，1:正常，0：禁用，-1：离会申请，-2：离会
	    if (status == 0) { // 禁用的成员
	      map = {
	        status: 0,
	        club_id: club_id
	      };
	    } else if (status == 1) { // 正常的成员
	    	map = {
	    	        status:1,
	    	        club_id: club_id
	    	      };
	    }else if (status ==2) { // 未审核的成员
	    	map = {
	    	        status:2,
	    	        club_id: club_id
	    	      };
	    }else if (status == -1) { // 离会申请
	    	map = {
	    	        status: -1,
	    	        club_id: club_id
	    	   };
	    }else if (status == -2) { // 已离会的会员
	    	map = {
	    	        status: -2,
	    	        club_id: club_id
	    	      };
	    } else {
	    	map = {
	    	        status: 1,
	    	        club_id: club_id
	    	 };
	    }

	    const data = await this.model('club_player').where(map).page(this.para('page')).order('create_time DESC').countSelect();
	    const html = this.pagination(data);
	    this.assign('pagination', html);
	    // 入会申请统计
	    const applynum = await this.model('club_player').where({
	      status:2,
	      club_id: club_id
	    }).count('id');
	    
	    // 离会申请统计
	    const leavenum = await this.model('club_player').where({
		      status:-1,
		      club_id: club_id
		}).count('id');
	    
	    this.assign('applynum', applynum);
	    this.assign('leavenum', leavenum);
	    this.assign('count', data.count);
	    this.assign('list', data.data);
	 // 当前位置
	    this.assign('status', status);
	    this.assign('clubid', club_id);
	    this.meta_title = '成员管理';
	    // 判断浏览客户端
	    if (this.isMobile) {
	      if (this.isAjax('get')) {
	        for (const v of data.data) {
	          v.create_time = this.moment(v.create_time).format('lll');
	        }
	        return this.json(data);
	      } else {
	        this.active = 'user/index';
	        return this.display(this.mtpl());
	      }
	    } else {
	      return this.display();
	    }
	}
  }
  
//查找我的玩家
  async searchplayerAction() {
	    const player_id = this.para('playerId') || null;
	    console.log('player_id ---------:'+player_id);
	    // 筛选订单
	    let map = {
	                 status: ['IN', [1]],
	                 uid: this.user.uid,
	                 player_id:player_id 
	    };

	    const data = await this.model('member_player').where(map).page(this.para('page')).order('bind_time DESC').countSelect();
	    // 判断浏览客户端
	    if (this.isMobile) {
	      if (this.isAjax('get')) {
	        return this.json(data);
	      } else {
	        this.active = 'player/index';
	        return this.display(this.mtpl());
	      }
	    } else {
	      return this.display();
	    }
  }
  
//俱乐部账户
  async accountAction() {
	if (this.isAjax('POST')) {
		const player_id = this.para('playerid') || null;
		const club_id = this.para('clubid') || null;
		const opt = this.para('opt') || null;
		if(opt==2){
			console.log('删除俱乐部成员--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).delete();
		    if (res) {
		    	// 删除俱乐部成员
		        return this.success({name:'删除成功！'});
		    }else{
		    	return this.fail('删除失败！');
		    }
		}else if(opt==0){
			console.log('设为管理员--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({is_admin:1});
			if (res) {
		    	// 设为管理员
		        return this.success({name:'设为管理员成功！'});
		    }else{
		    	return this.fail('设为管理员失败！');
		    }
		}else if(opt==1){
			console.log('取消管理员--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({is_admin:0});
			if (res) {
		    	// 取消管理员
		        return this.success({name:'取消管理员成功！'});
		    }else{
		    	return this.fail('取消管理员失败！');
		    }
		}else if(opt==3){
			console.log('同意入会--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({status:1});
			if (res) {
		    	// 同意入会
		        return this.success({name:'同意入会成功！'});
		    }else{
		    	return this.fail('同意入会失败！');
		    }
		}else if(opt==4){
			console.log('拒绝入会--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({status:3});
			if (res) {
		    	// 拒绝入会
		        return this.success({name:'拒绝入会成功！'});
		    }else{
		    	return this.fail('拒绝入会失败！');
		    }
		}else if(opt==5){
			console.log('同意离会--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({status:-2});
			if (res) {
		    	// 同意入会
		        return this.success({name:'同意离会成功！'});
		    }else{
		    	return this.fail('同意离会失败！');
		    }
		}else if(opt==6){
			console.log('拒绝离会--player_id:'+player_id+' club_id'+club_id);
			const res = await this.model('club_player').where({club_id:club_id, player_id:player_id}).update({status:1});
			if (res) {
		    	// 拒绝入会
		        return this.success({name:'拒绝离会成功！'});
		    }else{
		    	return this.fail('拒绝离会失败！');
		    }
		}
		
	}else{
		const club_id = this.para('clubid') || null;
	    // 筛选
	    const clubInfo = await this.model('club').find(club_id);
	    this.assign('clubInfo', clubInfo);
	    this.meta_title = '俱乐部账户';
	    // 判断浏览客户端
	    if (this.isMobile) {
	      if (this.isAjax('get')) {
	        for (const v of data.data) {
	          v.create_time = this.moment(v.create_time).format('lll');
	        }
	        return this.json(data);
	      } else {
	        this.active = 'center/club/index';
	        return this.display(this.mtpl());
	      }
	    } else {
	      return this.display();
	    }
	}
  }
};